﻿using Blazui.Component;
using Blazui.Component.Model;
using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using Project13776616780_01.Model;
using Project13776616780_01.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

namespace Project13776616780_01.Pages.Adv
{
    public partial class List
    {
        [Inject]
        private DocsDbContext dbContext { get; set; }
        private List<AdvModel> datas = new List<AdvModel>();

        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            await RefreshAsync();
        }

        private async Task RefreshAsync()
        {
            datas = (await dbContext.Set<Model.Adv>().OrderBy(x => x.Id).ToListAsync()).Select(x => new AdvModel()
            {
                Url = x.Url,
                Image = new UploadModel[] {
                new UploadModel()
                {
                     Url=x.Image
                }
                },
                Id = x.Id
            }).ToList();
            await InvokeAsync(Refresh);
        }

        private async Task ShowCreateWindowAsync()
        {
            var result = await DialogService.ShowDialogAsync<Create>("创建广告");
            await RefreshAsync();
        }

        private async Task ShowUpdateWindowAsync(object data)
        {
            var parameters = new Dictionary<string, object>();
            parameters.Add(nameof(Update.Data), data);
            var result = await DialogService.ShowDialogAsync<Update>("修改广告", parameters);
            await RefreshAsync();
        }

        private async Task DeleteAsync(object category)
        {
            var confirmResult = await ConfirmAsync("这将删除该广告，确认？");
            if (confirmResult != MessageBoxResult.Ok)
            {
                return;
            }
            var existCategory = (AdvModel)category;
            dbContext.Advs.RemoveRange(dbContext.Advs.Where(x => x.Id == existCategory.Id));
            await dbContext.SaveChangesAsync();
            await RefreshAsync();
        }
    }
}
